// packageFT/guide/order-detail/order-detail.js
const app = getApp()
import { dateRange, formatTime, timeDiff } from '../../../utils/util'
import { travelToolEnum } from '../../../utils/dataEnum'
// 增值项支付状态
const surchargeStatusEnum = {
  0: '未支付',
  1: '已支付' 
}
const addedFee = [
  {id: 1, name: '高速费', fee: 200 },
  {id: 2, name: '租车费(4天)', fee: 100 },
  {id: 3, name: '门票(3大人1儿童)', fee: 300 }
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailData: {},
    addedFee,
    surcharge: {},
    surchargeStatusEnum,
    travelToolEnum,
    oid: 0,
    loading: false,
    btnDisabledFinishItinerary: false,
    btnDisabledStartItinerary: false
  },

  /**
   * 获取订单详情
   * @param {Function} callback 
   */
  getDetail: function(callback) {
    this.setData({ 
      detailData: {},
      surcharge: {}
    })
    const { oid } = this.data
    if(!oid) return
    const urlStr = app.getNetAddresss('plugin.guide.frontend.order.guide.detail')
    const data = { oid }
    const _this = this
    wx.showLoading({
      title: '数据加载中...',
    })
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          let result = resData.data
          // 出行时间
          result.timeRange = dateRange(result.start_at, result.finish_at)
          _this.setData({ 
            detailData: result,
            surcharge: result.has_one_surcharge || {}
          })
          const nowStr = formatTime(new Date())
          // 距开始时间的秒数
          const distanceStart = timeDiff(nowStr, result.start_at, 'millisecond')
          // 距结束时间的秒数
          const distanceFinish = timeDiff(nowStr, result.finish_at, 'millisecond')
          if (
            // 订单不是【待服务】状态
            result.status != 1 || 
            // 未到出行开始时间
            distanceStart > 0
          ) {
            _this.setData({ btnDisabledStartItinerary: true })
          }
          if (
            // 订单不是【待服务】状态
            result.status != 2 || 
            // 未到出行结束时间
            distanceFinish > 0
          ) {
            _this.setData({ btnDisabledFinishItinerary: true })
          }
        } else {
          app.tips(resData.msg || '数据加载失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        callback && callback()
      }
    })
  },

  /**
   * 跳转到增值项
   */
  goEditAddedFee: function() {
    const { oid, surcharge, detailData } = this.data
    const { status, status_name } = detailData
    if (status == 0 || status == 1) {
      app.tips('行程未开始')
      return
    }
    else if (status == 3) {
      app.tips('行程已结束')
      return
    } else if (status != 2) {
      // 订单不是【已开始】状态
      app.tips(`订单${status_name}`)
      return
    }
    let list = []
    if (Object.keys(surcharge).length) {
      list = surcharge.options
    }
    const params = {
      oid, list
    }
    wx.navigateTo({
      url: '/packageFT/guide/add-added-fee/add-added-fee?params=' + encodeURIComponent(JSON.stringify(params)),
    })
  },

  /**
   * 行程开始
   */
  itineraryStart: function() {
    const { detailData, oid } = this.data
    const { status, status_name, start_at } = detailData
    if (!status) {
      app.tips('无订单信息！')
      return
    }
    // 订单不是【待服务】状态 
    if (detailData.status != 1) {
      app.tips(`订单${status_name}`)
      return
    }
    // 订单未支付
    if (detailData.has_one_order.has_one_pay_type.code == 'unPay') {
      app.tips(`订单未支付`)
      return
    }
    const nowStr = formatTime(new Date())
    // 距开始时间的秒数
    const distanceStart = timeDiff(nowStr, start_at, 'millisecond')
    if (distanceStart > 0) {
      app.tips('未到出行开始时间！')
      return
    }
    const _this = this
    wx.showModal({
      title: '提示',
      content: '是否确定开始行程？',
      complete: (cRes) => {
        if (cRes.confirm) {
          const urlStr = app.getNetAddresss('plugin.guide.frontend.need-order-operate.start')
          _this.setData({ loading: true })
          wx.showLoading({ title: '加载中...' })
          app._postNetWork({
            url:urlStr,
            data: { order_id: oid},
            success: function(res) {
              const resData = res.data
              if (resData.result == 1) {
                app.tips('行程已开始！')
                _this.getDetail()
              } else {
                app.tips(resData.msg || '请求失败！')
              }
            },
            complete: function() {
              wx.hideLoading()
              _this.setData({ loading: false })
            }
          })
        }
      }
    })
  },

  /**
   * 结束行程
   */
  itineraryOver: function() {
    const { detailData, oid } = this.data
    const { status, status_name, finish_at } = detailData
    if (!status) {
      app.tips('无订单信息！')
      return
    } else if (status != 2) {
      app.tips(`订单${status_name}`)
      return
    } else if (detailData.has_one_surcharge && detailData.has_one_surcharge.status == 0) {
      app.tips('用户未支付增值费')
      return
    }
    const nowStr = formatTime(new Date())
    // 距结束时间的秒数
    const distanceStart = timeDiff(nowStr, finish_at, 'millisecond')
    // 23小时59分59秒的毫秒数
    const oneDay = (23 * 60 * 60 + 59 * 60 + 59) * 1000
    // 结束时间为23:59:59，判断是否到行程结束时间为当天的00:00:00，所以判断是否到行程结束时间到条件为：当前时间 - 行程结束时间的毫秒数是否大于oneDay
    if (distanceStart > oneDay) {
      app.tips('未到行程结束时间！')
      return
    }
    const _this = this
    wx.showModal({
      title: '提示',
      content: '是否确定结束行程？',
      complete: (cRes) => {
        if (cRes.confirm) {
          const urlStr = app.getNetAddresss('plugin.guide.frontend.need-order-operate.guide-end')
          _this.setData({ loading: true })
          wx.showLoading({ title: '加载中...' })
          app._postNetWork({
            url:urlStr,
            data: { oid },
            success: function(res) {
              const resData = res.data
              if (resData.result == 1) {
                app.tips('行程已结束！')
                _this.getDetail()
              } else {
                app.tips(resData.msg || '请求失败！')
              }
            },
            complete: function() {
              wx.hideLoading()
              _this.setData({ loading: false })
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ oid: options?.oid})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDetail()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getDetail(() => wx.stopPullDownRefresh())
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})